<template>
  <div>
    <selector 
      :is-show="isProvinceShow"
      :provinces="provinces"
      default-title="请选择-省"
      code-key="provinceCode"
      code-name="provinceName"
      @handleChange="(e) => this.handleProvinceChange(e)"
    ></selector>
    <selector
      :is-show="isCityShow"
      :provinces="cities"
      default-title="请选择-市"
      code-key="cityCode"
      code-name="cityName"
      @handleChange="(e) => this.handleCityChange(e)"
    ></selector>
    <selector
      :is-show="isCountyShow"
      :provinces="counties"
      default-title="请选择-区县"
      code-key="countyCode"
      code-name="countyName"
      @handleChange="(e) => this.handleCountyChange(e)"
    ></selector>
  </div>
</template>
<script>
import Selector from './selector.vue';
import cityInfo from './cityInfo';
import {handleFormatData} from './utils';
export default {
  components: {
    Selector,
  },
  data() {
    return {
      provinces: null,
      cities: null,
      counties: null,
      selectedInfo: {
        province: null,
        city: null,
        county: null,
      }
    }
  },
  computed: {
    isProvinceShow() {
      return !!this.provinces
    },
    isCityShow() {
      return !!this.cities
    },
    isCountyShow() {
      return !!this.counties
    }
  },
  mounted() {
    this.provinces = handleFormatData(cityInfo);
  },
  methods: {
    handleProvinceChange(e) {
      let {value} = e.target;
      if (!value) {
        this.cities = null;
        this.counties = null;
        this.selectedInfo.province = null;
        this.selectedInfo.city = null;
        this.selectedInfo.county = null;
        return 
      }
      let [code, name] = value.split(':');
      this.cities = this.provinces[name].cities;
      this.selectedInfo.province = {
        code,
        name
      }
    },
    handleCityChange(e) {
      let {value} = e.target;
      if (!value) {
        this.counties = null;
        this.selectedInfo.city = null;
        this.selectedInfo.county = null;
        return 
      }
      let [code, name] = value.split(':');
      this.counties = this.cities[name].counties;
      this.selectedInfo.city =  {
        code,
        name
      }
    },
    handleCountyChange(e) {
      let {value} = e.target;
      if (!value) {
        this.selectedInfo.county = null;
        let {province, city, county} = this.selectedInfo;
        console.log(province?.name, city?.name, county?.name);
        return 
      }
      let [code, name] = value.split(':');
      this.selectedInfo.county = {
        code,
        name
      }
      let {province, city, county} = this.selectedInfo;
      console.log(province?.name, city?.name, county?.name);
    },
  }
}
</script>